require('dotenv').config();
const Koa = require('koa');
const KoaStaticCache = require('koa-static-cache');
const bodyParser = require('koa-bodyparser');
const authRoutes = require('./routes/authRoutes');
const userRoutes = require('./routes/userRoutes');
const taskRoutes = require('./routes/taskRoutes');
const cors = require('@koa/cors');

const app = new Koa();

app.keys = [process.env.COOKIE_SECRET]; // ywt
app.use(async (ctx, next) => {
  try {
    ctx.state.user = JSON.parse(ctx.cookies.get('user', {
      signed: true
    })); // encodeURI / decodeURI
  } catch(err) {
    // ctx.throw(401, '没有权限');
  }

  await next();
});


// 静态代理
app.use(KoaStaticCache({
  prefix: '/public',
  dir: './public',
  dynamic: true,
  gzip: true
}));

// 使用 bodyParser 中间件来解析请求体
app.use(bodyParser());

/**
 * 使用路由
 */
app.use(authRoutes.routes());
app.use(authRoutes.allowedMethods());

app.use(userRoutes.routes());
app.use(userRoutes.allowedMethods());

app.use(taskRoutes.routes());
app.use(taskRoutes.allowedMethods());

app.use(cors());

/**
 * 启动服务器
 */
const PORT = 3010;
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});